package com.ytjj.qmyx.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.cmpp.OperatorJudgeUtil;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.dto.mqdto.PrepaidRefillDto;
import com.ytjj.common.exception.ApiException;
import com.ytjj.qmyx.admin.dao.PhoneRechargeDao;
import com.ytjj.qmyx.admin.dao.ReturnRechargeDao;
import com.ytjj.qmyx.admin.eunm.PhoneRechargeGiveFlagEnum;
import com.ytjj.qmyx.admin.model.request.ReturnRechargeRequest;
import com.ytjj.qmyx.admin.model.response.RechargeNeedResponse;
import com.ytjj.qmyx.admin.model.response.ReturnRechargeResponse;
import com.ytjj.qmyx.admin.service.ReturnRechargeService;
import com.ytjj.qmyx.mall.model.PhoneRecharge;
import com.ytjj.qmyx.mall.model.RechargeRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;

/**
 * @Description TODO
 * @ClassName ReturnRechargeServiceImpl
 *
 * 
 * @Version 1.0
 **/
@Service
@Slf4j
public class ReturnRechargeServiceImpl implements ReturnRechargeService {

    @Resource
    private ReturnRechargeDao returnRechargeDao;
    @Resource
    private PhoneRechargeDao phoneRechargeDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public CommonPage<ReturnRechargeResponse> selectList(ReturnRechargeRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        return CommonPage.restPage(returnRechargeDao.selectList(request));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditRecharge(Integer orderinfoId, Integer rechargeStatus) {
        // 审核成功才执行充值接口
        log.info("===充值话费审核==={},{}", orderinfoId, rechargeStatus);
        if (rechargeStatus == 1) {
            // 2.充值
            RechargeNeedResponse needResponse = returnRechargeDao.getRechargeInfo(orderinfoId);
            log.info("===needResponse==={}", needResponse);
            if (null == needResponse) {
                throw new ApiException("找不到需要审核的信息！");
            }
            if (!needResponse.getRechargeStatus().equals(0)) {
                throw new ApiException("充值状态异常，不能审核！");
            }
            if (needResponse.getOrderInfoStatus().equals(4) || needResponse.getOrderInfoStatus().equals(5) || needResponse.getOrderInfoStatus().equals(6)) {
                throw new ApiException("订单状态异常，不能审核！");
            }
            RechargeRequest rechargeRequest = new RechargeRequest();
            rechargeRequest.setPhoneNo(needResponse.getPhone());
            BigDecimal money = needResponse.getMoney().multiply(new BigDecimal(100)).setScale(0, RoundingMode.DOWN);

            String operators = checkOperator(needResponse.getPhone());
            //创建充值订单
            boolean result = createPhoneRecharge(needResponse.getPhone(), operators, needResponse.getPaySource(), money.intValue(),
                    needResponse.getMoney().intValue(), money.intValue(), needResponse.getTradeType(), needResponse.getOrderNo(),
                    orderinfoId, needResponse.getOrderSource(), needResponse.getChannel());
            if (!result) {
                throw new ApiException("系统异常，请稍后重试！");
            }

            PrepaidRefillDto prepaidRefillDto = new PrepaidRefillDto();
            prepaidRefillDto.setOrderNo(needResponse.getOrderNo());
            prepaidRefillDto.setOperators(operators);
            // 发送队列
            rabbitTemplate.convertAndSend(QueueConstants.RECHARGE_QUEUE, prepaidRefillDto);

        }else {
            //审核失败直接更新状态
            returnRechargeDao.auditRecharge(orderinfoId, rechargeStatus);
        }
    }

    private boolean createPhoneRecharge(String phone, String operators, String payType, Integer denomination,
                                       Integer giveIntegeral, Integer price, String type, String orderNo, Integer orderinfoId, String orderSource, String channel) {
        // 生成支付订单
        PhoneRecharge phoneRecharge = new PhoneRecharge();
        phoneRecharge.setOrderNo(orderNo);
        phoneRecharge.setPhone(phone);
        phoneRecharge.setOperators(operators);
        phoneRecharge.setPlatform(orderSource);
        phoneRecharge.setChannel(channel);
        phoneRecharge.setUuid(String.valueOf(orderinfoId));
        phoneRecharge.setStatus(3);                         // 支付中
        phoneRecharge.setPayType(payType);
        phoneRecharge.setDenomination(denomination);
        phoneRecharge.setGiveIntegral(giveIntegeral);
        phoneRecharge.setPrice(price);
        phoneRecharge.setErrorStatus(0);
        phoneRecharge.setCreateTime(new Date());
        phoneRecharge.setType("APP-" + type);
        phoneRecharge.setGiveFlag(PhoneRechargeGiveFlagEnum.GIVE.getValue());
        int result = phoneRechargeDao.insert(phoneRecharge);
        return result > 0 ? true : false;
    }

    /**
     * 根据手机号获取运营商
     * @param phone
     * @return
     */
    private String checkOperator(String phone) {
        String result = null;
        String businessOperator = OperatorJudgeUtil.checkOperator(phone);
        switch (businessOperator) {
            case "mobile":
                result = "01";
                break;
            case "unicom":
                result = "02";
                break;
            case "telecom":
                result = "03";
                break;
            default:
                result = "unknown";
                break;
        }
        return result;
    }
}